package p2pscrabble;

public class P2PScrabble {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String myName = "player";
		boolean isHost;
		String ipAddress = "localhost";
		int port = 1234;
		
		if (args.length > 0) {
			try {
			myName = args[0];
			ipAddress = args[1];
			port = Integer.parseInt(args[2]);
			}
			catch (Exception e) {
				myName = "player";
				ipAddress = "localhost";
				port = 1234;
			}
		}
		
		// start the login window
		LoginWindow start = new LoginWindow(myName, ipAddress, port);

		while (start.getConnectionStatus() != LoginWindow.CONNECTED) {
			// do nothing
			try {
				// Poll every ~10 ms
				Thread.sleep(10);
			} catch (InterruptedException e) {
			}
		}

		Connection connection = start.getConnection();
		myName = start.getMyName();
		isHost = start.isHost();
		String filename = start.getFileName();
		System.out.println(filename);

		// close the login window
		start.dispose();

		// exchange name
		connection.send_data(myName);
		String oppName = connection.receive_data();

		String player1name = null;
		String player2name = null;

		if (isHost) {
			player1name = myName;
			player2name = oppName;
		} else {
			player1name = oppName;
			player2name = myName;
		}

		System.out.println(player1name + " vs " + player2name);

		// check if want to start new game / load
		boolean newGame = false;
		connection.send_data(filename);
		newGame = connection.receive_data().contains("@#$") ? true : newGame;

		// initiate new game
		if (newGame) {
			new Game(connection, player1name, player2name, isHost, null);
		}

		// validate save game
		else {
			SaveGameValidator sgv = new SaveGameValidator(connection, filename);

			if (sgv.validateSaveGame())
				new Game(connection, player1name, player2name, isHost, sgv
						.getMy());
			else {
				new InfoWindow(100, "Save game not valid",
						"Your save game is not valid. The program will close");
			}
		}
	}
}
